const Router = require('@koa/router')
const proxy = require('koa-better-http-proxy')

const router = new Router()
/**
 * 转发静态资源 主要是js文件
 */
const handleProxy = proxy('https://res.wx.qq.com', {
  // 转发路径处理
  proxyReqPathResolver(ctx) {
    // 去掉/res
    return ctx.url.substring(4)
  },
  // 修改请求头
  proxyReqOptDecorator(proxyReqOpts) {
    proxyReqOpts.headers.Host = 'res.wx.qq.com'
    proxyReqOpts.headers['accept-encoding'] = 'gzip'
    return proxyReqOpts
  },
  // 修改返回内容
  userResDecorator(proxyRes, proxyResData) {
    const data = proxyResData.toString('utf8')
    return (
      data
        // e.crossOrigin = "anonymous",
        .replace(/e.crossOrigin="anonymous",/g, '')
        .replace(/e.crossOrigin="anonymous"/g, 'true')
        // crossorigin: "anonymous",
        .replace(/crossorigin:"anonymous",/g, '')
    // A.setAttribute("crossOrigin", "Anonymous")
    // .replace(/A.setAttribute\("crossOrigin","Anonymous"\),/g, "")
    // .replace(/A.setAttribute\("crossOrigin","Anonymous"\)/g, "")
    )
  }
})

router.get(/^\/res/, handleProxy)

module.exports = router.routes()
